package com.android.takagism.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.takagism.R;
import com.android.takagism.service.ClientService;
import com.android.takagism.utils.Clue;
import com.android.takagism.utils.EasyPuzzle;
import com.android.takagism.utils.MiddlePuzzle;
import com.android.takagism.utils.MyContext;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class UserMainActivity extends AppCompatActivity implements View.OnClickListener {

    private MyContext myContext = MyContext.getInstance();
    private String puzzle_question;
    private String puzzle_answer;
    private int hardLevel = (int) myContext.getStatics("hardLevel");

    //    private MediaPlayer mp = new MediaPlayer();//MediaPlayer.create(this, R.raw.case1);
    MediaPlayer mp = null;
    private boolean isRelease = true;
    private boolean isCountDown = false;

    ClientService clientService;
    public static Handler mainHandler;

    private ImageButton giveUpBtn;
    private ImageButton lookHistoryBtn;
    private Button needHelpBtn;
    private Button helpRequestBtn;
    private Button commitAnsBtn;
    private EditText currentQuestion;
    private EditText myAns;
    private EditText clueInfo_last;
    private EditText gotHelpInfo;
    private ImageView clueImg_last;
    private ProgressBar progressBar;

    private CountDownTimer countDownTimer;
    private EasyPuzzle this_easyPuzzle;
    private MiddlePuzzle this_middlePuzzle;
    private Clue this_Clue;
    private LinkedList<Clue> allClues;


    private int helpCount = 0;
    private int commitCount = 0;
    private final Random random = new Random(100000);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_main);
        Intent intent = getIntent();
        this_Clue = (Clue) intent.getExtras().get("new_clue");
        System.out.println(this_Clue);
        init();
    }

    private void init() {
        initMainHandler();

        Clue lastClue = null;
        allClues = (LinkedList<Clue>) myContext.getAllClues("update_clues");
        if (allClues == null) {
            allClues = new LinkedList<>();
        } else {
            lastClue = allClues.getLast();
        }
//        allClues.add(this_Clue);
//        myContext.setAllClues("update_clues", allClues);解答了才能放进更新

        clueInfo_last = findViewById(R.id.clue_info);
        clueImg_last = findViewById(R.id.clue_img);
        if (lastClue == null) {
            clueInfo_last.setText("这是第一个问题\n解决问题将获得线索");
        } else {
            clueInfo_last.setText(lastClue.getClue());
            clueImg_last.setBackground(getDrawable(lastClue.getImageId()));
        }


        gotHelpInfo = findViewById(R.id.got_help_info);


        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        clueInfo_last.setWidth(displayMetrics.widthPixels / 2);
        gotHelpInfo.setWidth(displayMetrics.widthPixels / 2);


        giveUpBtn = findViewById(R.id.give_up_btn);
        giveUpBtn.setOnClickListener(this);
        lookHistoryBtn = findViewById(R.id.look_history_btn);
        lookHistoryBtn.setOnClickListener(this);
        helpRequestBtn = findViewById(R.id.urgentHelp);
        helpRequestBtn.setOnClickListener(this);
        needHelpBtn = findViewById(R.id.need_help);
        needHelpBtn.setOnClickListener(this);
        commitAnsBtn = findViewById(R.id.commit_ans);
        commitAnsBtn.setOnClickListener(this);
        currentQuestion = findViewById(R.id.current_question);
        myAns = findViewById(R.id.write_ans);
        progressBar = findViewById(R.id.progressBar);

        clientService = (ClientService) myContext.getStatics("clientService");

        int Max_Time = 30000;
        countDownTimer = new CountDownTimer(Max_Time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
//                System.out.println("剩余时间(百分比):" + millisUntilFinished / 300);
                progressBar.setProgress((int) (millisUntilFinished / (Max_Time / 100)));
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onFinish() {
                System.out.println("计时结束");
                isCountDown = false;
                progressBar.setProgress(0);
                currentQuestion.setText("DEFEAT!");
                commitAnsBtn.setClickable(false);
            }
        };
        getNewPuzzle();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.give_up_btn:
                GiveUpFun();
                break;
            case R.id.look_history_btn:
                ShowHistoryFun();
                break;
            case R.id.urgentHelp:
                SendHelpRequest();
                break;
            case R.id.need_help:
                GiveSolveHelpFun();
                break;
            case R.id.commit_ans:
                CommitAnsFun();
                break;
            default:
                break;
        }
    }

    private void MusicPlay(int Max_Time) {
        Max_Time *= 1000;
        mp = MediaPlayer.create(this, R.raw.case1);
        mp.start();

        CountDownTimer musicTime = new CountDownTimer(Max_Time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                System.out.println("剩余s" + millisUntilFinished / 1000);
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onFinish() {
                System.out.println("计时结束");
                mp.stop();
                isRelease = true;
            }
        };
        musicTime.start();
    }

    private void SendHelpRequest() {
        System.out.println("sendHelpRequest" +
                "与服务器进行聊天");
        CommunicationSubView();
    }

    private void GiveUpFun() {
        System.out.println("giveUpThisGame" +
                "放弃解题");
        if (isCountDown) countDownTimer.cancel();
        currentQuestion.setText("断开连接！\n" +
                "即将返回上一界面");
        finish();
    }

    private void ShowHistoryFun() {
        System.out.println("showHistory");
        if (isCountDown)
            countDownTimer.cancel();
        startActivity(new Intent(UserMainActivity.this, MyCluesActivity.class));
    }

    private void GiveSolveHelpFun() {
        System.out.println("sendHelpRequest" +
                "给出几个错误选项，对话框选择题" +
                "超过三次直接给答案");


        if (helpCount > 3) {
            myAns.setText(puzzle_answer);

            helpCount = 0;
        } else {
            String[] strs = new String[4];
            for (int i = 0; i < 4; i++) {
                strs[i] = errorAnswers.get(i);
            }
            strs[random.nextInt(4)] = puzzle_answer;
            System.out.println(" 提示列表: " + strs);
            AlertDialog.Builder builder = new AlertDialog.Builder(UserMainActivity.this);
            builder.setTitle("正确答案在以下选项中")
//                    .setMessage()
                    .setSingleChoiceItems(strs, 0, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            myAns.setText(strs[which]);
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ;
                        }
                    })
                    .setNegativeButton("自己输入", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            myAns.setText("");
                        }
                    });

            builder.create().show();
            helpCount++;
        }
    }

    private void CommitAnsFun() {
        System.out.println("commitAns" +
                "答案正确？=>进度条清零" +
                "下一条问题到来时再开始");
        if (commitCount > 3) {
            myAns.setText(puzzle_answer);
            ToastShow("超过最多提交次数!\n已显示正确答案");
            commitCount = 0;
            return;
        }
        if (myAns.getText().toString().equals(puzzle_answer)) {
            if (isCountDown) countDownTimer.cancel();
//           ===================================================================================
//            clientService.sendMsg("请求下一个线索" +
//                    "Handler中获取读取到的信息，即线索" +
//                    "再赋值给当前puzzle");
//            ===================================================================================
            allClues.add(this_Clue);
            myContext.setAllClues("update_clues", allClues);
//            解答了才能放进更新
            //发送解决了问题的消息
            MusicPlay(6);
            BeforeUserMainActivity.mainHandler.sendEmptyMessage(0x1114);
            commitCount = 0;
            ToastShow("答案正确！");
            finish();
        } else {
            commitCount++;
            ToastShow("答案错误！");
        }
    }

    private LinkedList<String> errorAnswers;

    private void getNewPuzzle() {
        System.out.println("生成新的puzzle");
        LinkedList<Clue> clues = (LinkedList<Clue>) myContext.getAllClues("update_clues");
        switch (hardLevel) {
            case 1:
                EasyPuzzle puzzle = new EasyPuzzle(this_Clue);
                errorAnswers = puzzle.product4Errors();
                puzzle_question = puzzle.getQuestion();
                puzzle_answer = (String) puzzle.getAnswer();

                break;
            case 2:
                MiddlePuzzle middlePuzzle = new MiddlePuzzle(this_Clue);
                errorAnswers = middlePuzzle.product4Errors();
                puzzle_question = middlePuzzle.getQuestion();
                puzzle_answer = (String) middlePuzzle.getAnswer();
                break;
            case 3:
                MiddlePuzzle hardPuzzle = new MiddlePuzzle(this_Clue);
                errorAnswers = hardPuzzle.product4Errors();
                puzzle_question = hardPuzzle.getQuestion();
                puzzle_answer = (String) hardPuzzle.getAnswer();
                break;
            default:
                break;
        }
        currentQuestion.setText(puzzle_question);
        helpCount = 0;
        commitCount = 0;
        if (isCountDown) countDownTimer.cancel();
        countDownTimer.start();
    }

    @SuppressLint("HandlerLeak")
    public void initMainHandler() {

        mainHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {

                // 接收子线程的消息
                switch (msg.what) {
                    case 0x1111://接收服务器，主要是场外求助数据
                        String tmp_str = msg.obj.toString();
                        System.out.println("----------------接收到服务器发送数据： " + tmp_str);
                        gotHelpInfo.append("ADMIN回应:" + tmp_str + "\n");
                        break;
                    case 0x1113:
                        ToastShow("失去连接...");
                        finish();
                        break;
                    default:
                        break;
                }

            }

        };
    }

    public void ToastShow(String msg) {
        @SuppressLint("ShowToast") Toast toast = Toast.makeText(UserMainActivity.this, msg, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        showMyToast(toast, 500);

    }

    public static void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3500);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);

    }


    private void CommunicationSubView() {
        EditText inputInfo = new EditText(UserMainActivity.this);
        inputInfo.setBackground(getDrawable(R.drawable.my_edit_bg));
        AlertDialog.Builder builder = new AlertDialog.Builder(UserMainActivity.this);
        builder.setTitle("请输入求助的具体内容")
                .setView(inputInfo)
                .setPositiveButton("发送！", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String msg = inputInfo.getText().toString();
                        clientService.sendMsg(clientService.getClient().toString().substring(0, 25) + "]@:" + msg);
                    }
                })
                .setNegativeButton("算了", null);
        builder.create().show();
    }
}